package com.winit.openapi.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;

/**
 * 面单解析
 * TODO long.yue: Change to the actual description of this class
 * 
 * @version Revision History
 * 
 *          <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月13日     Created
 * 
 * </pre>
 * @since 1.
 */
public class WinitLabelParser {
    
    private static final Logger logger = LoggerFactory.getLogger(WinitLabelParser.class);

    private HttpClient    httpClient = null;
    private BASE64Encoder encoder;

    public WinitLabelParser() {
        this.httpClient = new HttpClient();
        this.encoder = new BASE64Encoder();
    }

    /**
     * 根据URL获取winitlabel
     * TODO Add comments here.
     * 
     * @param charset
     * @return
     */
    public String getWinitLabelByURL(String url){
        HttpMethod httpMethod = new GetMethod(url);
        InputStream is = null;
        try{
            int status = httpClient.executeMethod(httpMethod);
            if (status == HttpStatus.SC_OK) {
                is = httpMethod.getResponseBodyAsStream();
                byte[] arr = IOUtils.toByteArray(is);
                String s = encoder.encode(arr);
                return s;
            } else {
                throw new ApiException(ErrorCode.CONNECT_FAILED);
            }
        }catch(Exception e){
            logger.error("getWinitLabelByURL error:",e);
            throw new ApiException(ErrorCode.DOWNLOAD_FILE_ERROR);
        }finally{
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
